package at.fhj.itm11.forum.controller;

import java.util.Date;

import javax.annotation.PostConstruct;
import javax.enterprise.inject.Model;
import javax.enterprise.inject.Produces;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import org.primefaces.model.UploadedFile;

import at.fhj.itm11.forum.beans.AuthenticationBean;
import at.fhj.itm11.forum.beans.TopicBean;
import at.fhj.itm11.forum.model.Post;
import at.fhj.itm11.forum.model.Topic;
import at.fhj.itm11.forum.model.User;
import at.fhj.itm11.forum.service.PostRegistration;


@Model
public class PostController {
	
	@Inject
	private TopicBean topicBean;
	
	@Inject
	private AuthenticationBean authBean;
	
	@Inject
	private PostRegistration postRegistration;
	 
	@Produces
	@Named
	private Post newPost;
	
	private UploadedFile image;
	private UploadedFile video;
	 
	@PostConstruct
	public void initNewPost() {
		newPost = new Post();
	}
	 
	public String register() throws Exception {
		FacesContext context = FacesContext.getCurrentInstance();
		
		try {
			if (newPost.getTitle() == null || "".equals(newPost.getTitle())) {
				context.addMessage("addPost:title", new FacesMessage(
						FacesMessage.SEVERITY_ERROR, "Creation failed", "Title must not be empty!"));
			} else if (newPost.getText() == null || "".equals(newPost.getText())) {
				context.addMessage("addPost:text", new FacesMessage(
						FacesMessage.SEVERITY_ERROR, "Creation failed", "Text must not be empty!"));
			} else {
				boolean valid = true;
				
				
				if (!"".equals(image.getFileName())) {
					if (image.getContentType().startsWith("image/")) {
						byte[] byteFile = new byte[image.getContents().length];
						System.arraycopy(image.getContents(), 0, byteFile, 0, image.getContents().length);
						newPost.setImage(byteFile);
					} else {
						context.addMessage("addPost:image", new FacesMessage(
								FacesMessage.SEVERITY_ERROR, "Creation failed", "Only images are allowed!"));
						valid = false;
					}
				}
				
				if (!"".equals(video.getFileName())) {
					if (video.getContentType().startsWith("video/")) {
						byte[] byteFile = new byte[video.getContents().length];
						System.arraycopy(video.getContents(), 0, byteFile, 0, video.getContents().length);
						newPost.setVideo(byteFile);
					} else {
						context.addMessage("addPost:video", new FacesMessage(
								FacesMessage.SEVERITY_ERROR, "Creation failed", "Only videos are allowed!"));
						valid = false;
					}
				}
				
				if (valid) {
					newPost.setDate(new Date());
					newPost.setTopic(topicBean.getCurrentTopic());
					newPost.setUser(authBean.getCurrentUser());
					
					postRegistration.register(newPost);
					context.addMessage(null, new FacesMessage(
							FacesMessage.SEVERITY_INFO, "Post creation successful!",
							"Creation successful"));
					
					return "showPosts?faces-redirect=true&id=" + newPost.getTopic().getId();
				}
			}
		} catch (Exception e) {
			String errorMessage = getRootErrorMessage(e);
			context.addMessage(null, new FacesMessage(
					FacesMessage.SEVERITY_ERROR, errorMessage,
					"Creation failed"));
		}
		
		return null;
	}

	private String getRootErrorMessage(Exception e) {
		// Default to general error message that registration failed.
		String errorMessage = "Registration failed. See server log for more information";
		if (e == null) {
			// This shouldn't happen, but return the default messages
			return errorMessage;
		}

		// Start with the exception and recurse to find the root cause
		Throwable t = e;
		while (t != null) {
			// Get the message from the Throwable class instance
			errorMessage = t.getLocalizedMessage();
			t = t.getCause();
		}
		// This is the root cause message
		return errorMessage;
	}

	public UploadedFile getImage() {
		return image;
	}

	public void setImage(UploadedFile image) {
		this.image = image;
	}
	
	public UploadedFile getVideo() {
		return video;
	}

	public void setVideo(UploadedFile video) {
		this.video = video;
	}
}